package com.android.vestel.photoroid;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import android.content.Context;
import android.util.Log;

public class SyncPhotos {
	PicasaClient picasaClient;
	FlickrClient flickrClient;
	DataHelper dataHelper;
	Context context;
	String ProgramState;
	private final String TAG = "SyncPhotos"; 
	String AlbumID;
	HashSet<String> imagesOnDB;
	HashMap<String,String> imagesOnAccount;
	HashSet<String> adds;
	HashSet<String> deletes;
	public static String downloadDir = "/sdcard/sdcard/photoroid/";

	public SyncPhotos(Context context) {
		this.context = context;
	}
	public boolean synchronize() {
		Log.e("SyncPhotos","Photo synchronization is started.");
		//get program state
		updateProgramState();
		//according to the program state choose what to do
	
		if (ProgramState.equals(PhotoroidService.PROG_STAT_PICASA_ENABLED)) {
			Log.e(TAG, "ProgramState = picasa enabled");
			openDBConnection();
			File temp = null;
			
			//create client
			if(picasaClient == null){
				picasaClient = new PicasaClient(dataHelper.selectAllOfAccounts().get(DataHelper.USERNAME),dataHelper.selectAllOfAccounts().get(DataHelper.PASSWORD));
			}
			//get album name
			Log.e(TAG, dataHelper.selectAllOfVar().toString());
			AlbumID = dataHelper.selectAllOfVar().get(DataHelper.ALBUM_ID);
			
			imagesOnDB = new HashSet<String>(dataHelper.getAllPhotoIDs());
			//if there is images that is not in the database delete them.
			
			if(picasaClient.OpenAuthentication()){
				//picasaClient.parseAlbumIDs();
				picasaClient.parsePhotos(AlbumID);
				imagesOnAccount = picasaClient.getImages();
				
				if(imagesOnAccount.size() > 0){
					adds = new HashSet<String>();
					adds.addAll(imagesOnAccount.keySet());
					adds.addAll(imagesOnDB);
					deletes = new HashSet<String>(adds);
					
					// the image ids that will be added
					adds.removeAll(imagesOnDB);
					
					// the image ids that will be deleted
					Log.e(TAG, "Images on db "+ imagesOnDB.size()+ " " + imagesOnDB.toString());
					Log.e(TAG, "Images on internet "+ imagesOnAccount.keySet().size()+ " " + imagesOnAccount.keySet().toString());
					deletes.removeAll(imagesOnAccount.keySet());
					
					openDBConnection();
					Log.e(TAG, "Images to be added "+ adds.size()+ " " + adds.toString());
					for(String photoID: adds){
						String url = imagesOnAccount.get(photoID);
						dataHelper.insertToPhotos(photoID, url, "0");
					}
					Log.e(TAG,"Images to be deleted "+deletes.size()+ " "+deletes.toString());
					for(String photoID: deletes){
						temp = new File(downloadDir + photoID + ".jpg");
						if(temp.exists()){
							temp.delete();
							dataHelper.deleteFromPhotosTable(photoID);
							Log.e(TAG,temp.getAbsolutePath()+" is deleted");
						}
						else {
							dataHelper.deleteFromPhotosTable(photoID);
						}
					}
					syncWithDir();
				}
				closeDBConnection();
				picasaClient = null;
				Log.e("SyncPhotos", "Synchronization Finished...");
				return true;
			}
		} else if (ProgramState.equals(PhotoroidService.PROG_STAT_FLICKR_ENABLED)) {
			Log.e(TAG, "ProgramState = flickr enabled");
			openDBConnection();
			File temp = null;
			
			//create client
			if(flickrClient == null){
				flickrClient = new FlickrClient(dataHelper.selectAllOfAccounts().get(DataHelper.USERNAME));
			}
			//get album name
			Log.e(TAG, dataHelper.selectAllOfVar().toString());
			
			imagesOnDB = new HashSet<String>(dataHelper.getAllPhotoIDs());
			if(flickrClient.is_valid()){
				flickrClient.getAllImages(); //fetch the image data from internet
				imagesOnAccount = flickrClient.getImages();
				
				if(imagesOnAccount.size() > 0){
					adds = new HashSet<String>();
					adds.addAll(imagesOnAccount.keySet());
					adds.addAll(imagesOnDB);
					deletes = new HashSet<String>(adds);
					
					// the image ids that will be added
					adds.removeAll(imagesOnDB);
					
					// the image ids that will be deleted
					Log.e(TAG, "Images on db "+ imagesOnDB.size()+ " " + imagesOnDB.toString());
					Log.e(TAG, "Images on internet "+ imagesOnAccount.keySet().size()+ " " + imagesOnAccount.keySet().toString());
					deletes.removeAll(imagesOnAccount.keySet());
					
					openDBConnection();
					Log.e(TAG, "Images to be added "+ adds.size()+ " " + adds.toString());
					for(String photoID: adds){
						String url = imagesOnAccount.get(photoID);
						dataHelper.insertToPhotos(photoID, url, "0");
					}

					Log.e(TAG,"Images to be deleted "+deletes.size()+ " "+deletes.toString());
					for(String photoID: deletes){
						temp = new File(downloadDir + photoID + ".jpg");
						if(temp.exists()){
							temp.delete();
							dataHelper.deleteFromPhotosTable(photoID);
							Log.e(TAG,temp.getAbsolutePath()+" is deleted");
						}
						else {
							dataHelper.deleteFromPhotosTable(photoID);
						}
					}
					syncWithDir();
				}
			}
			closeDBConnection();
			flickrClient = null;
			Log.e("SyncPhotos", "Synchronization Finished...");			
			return true;
		} else if (ProgramState.equals(PhotoroidService.PROG_STAT_EXTERNAL_ENABLED)) {
			Log.e(TAG, "ProgramState = external enabled");
			return true;
		} else {
			Log.e(TAG, "The program state is not defined.");
			//updateProgramState(PROG_STAT_DISABLED,"null");
			return false;
		}
		return false;
	}
	private void openDBConnection() {
		if (dataHelper == null) {
			dataHelper = new DataHelper(context);
		}
		Log.e("PicasaFormActivity","Database Connection Opened");
	}

	private void closeDBConnection() {
		if (dataHelper != null) {
			dataHelper.closeDB();
			dataHelper = null;
		}
		Log.e("PicasaFormActivity","Database Connection Closed");

	}
	private String updateProgramState() {
		openDBConnection();
		ProgramState = dataHelper.selectAllOfSetting().get(
				DataHelper.PROGRAM_STATE);
		closeDBConnection();
		return ProgramState;
	}
	private void syncWithDir(){
		File temp = null;
		ArrayList<String> adds = dataHelper.getPhotosNotDownloaded();
		Log.e(TAG,"Photos not downloaded = "+adds);
		openDBConnection();
		for(String photoID: adds){
			String url = imagesOnAccount.get(photoID);
			if((new File(downloadDir)).mkdir()){
				Log.e("WebPhotos","/sdcard/photoroid is created.");
			} else {
				Log.e("WebPhotos","/sdcard/photoroid exists");
			}
			if((new File(downloadDir)).exists()){
				temp = new File(downloadDir + photoID + ".jpg");
				if(!temp.exists() || temp.length() == 0){
					if(picasaClient != null){
						if(picasaClient.downloadFile(url,temp)){
							dataHelper.updatePhotosTable(photoID, url, "1");
						}						
					}
					if(flickrClient != null){
						if(flickrClient.downloadFile(url,temp)){
							dataHelper.updatePhotosTable(photoID, url, "1");
						}						
					}
				}
				else {
					dataHelper.updatePhotosTable(photoID, url, "1");
					Log.e("SyncPhotos",photoID + ".jpg"+" already exists. Nothing downloaded");
				}
			}else {
				Log.e("WebPhotos",photoID + ".jpg is not downloaded.");
			}
			//Toast.makeText(context, "Download Finished", Toast.LENGTH_SHORT);
		}
	}
}
